#!/usr/bin/perl -w
use strict;

# Import CPAN Modules
use DBI;
use Data::Dumper;
use CGI;

# Set global vars, these should never change during execution
my $user = "theodore";
my $pass = "ceixeeJ1";
my $source = "dbi:mysql:theodore;host=mussel.ucc.asn.au";


my $cgi = new CGI;
my @params = $cgi->param;

print "Content-Type: application/json", "\n\n";

eval {
my $search = $cgi->param('search');
$search =~ s/\s+/ /g;
$search =~ s/[^\w* ]//g;
$search =~ s/\*/%/g;

my @terms = split(' ',$search);

my $sql = 'SELECT category, GROUP_CONCAT(word SEPARATOR ", "), COUNT(*) * SUM(weight) AS weight FROM weights WHERE word LIKE "'. join("\" OR word like \"", @terms) . '" GROUP by category order by weight desc limit 20;';

my $dbh = DBI->connect($source, $user, $pass);

my $sth = $dbh->prepare($sql);

$sth->execute();

my $json = '{"results":[';
	while (my @vals = $sth->fetchrow_array()) {
		$json .= '{"category":"'.$vals[0].'", "matches":"'.$vals[1].'", "weight":"'.$vals[2].'"'. "},";
	}
	$json =~ s/,$//;
	$json .= ']}';

sleep(5);
print $json;

exit (0);
}; print '{"error":"'.$@.'"}'if $@;

